import re

from rest_framework import serializers
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer

from user.models import UserModel, GoodsModel, BannerModel, ShopModel


# Create your views here.
class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserModel
        fields = '__all__'


class GoodsSerializer(serializers.ModelSerializer):
    class Meta:
        model = GoodsModel
        fields = '__all__'


class CustomObtainTokenPairSerializer(TokenObtainPairSerializer):
    @classmethod
    def get_token(cls, user):
        token = super().get_token(user)
        token['username'] = str(user.username)
        return token


class RegisterSerializer(serializers.ModelSerializer):
    re_password = serializers.CharField(write_only=True)

    class Meta:
        model = UserModel
        fields = "__all__"

    def validate(self, attrs):
        re_password = attrs.get('re_password')
        password = attrs.get('password')
        username = attrs.get('username')
        print(password, re_password, username)
        if len(password) < 6 or len(password) > 16:
            raise serializers.ValidationError('密码长度必须在6-16位之间')
        if len(re_password) < 6 or len(re_password) > 16:
            raise serializers.ValidationError({'re_password': '密码长度必须在6-16位之间', "code": 400})
        # 判断密码是否一致
        if password != re_password:
            raise serializers.ValidationError("两次密码不一致")
        attrs.pop('re_password')
        return attrs

    def create(self, validated_data):
        try:
            # 判断传过来的username是手机号还是邮箱，还是用户名
            if re.match(r'^1[3-9]\d{9}$', validated_data['username']):
                validated_data['phone'] = validated_data['username']
            elif re.match(r'^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$', validated_data['username']):
                validated_data['email'] = validated_data['username']
            else:
                validated_data['username'] = validated_data['username']
            user = UserModel.objects.create_user(**validated_data)
            return user
        except Exception as e:
            print(f"Error in creation: {e}")
            raise
class BannersSerializer(serializers.ModelSerializer):
    class Meta:
        model = BannerModel
        fields="__all__"


class ShopModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = ShopModel
        fields="__all__"